package com.qq.weixin.mp.message.hxexp.controller;

import java.io.StringReader;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxexp.weixin.common.jaxb.JaxbMarshallerHelper;
import com.hxexp.weixin.common.jaxb.JaxbUnmarshallerHelper;
import com.hxexp.weixin.common.web.HttpUtil;
import com.hxexp.weixin.constant.PayNotifyStatus;
import com.qq.weixin.mp.message.hxexp.model.receive.PayNotifyJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.NotifyResponseJaxb;

/**
 * 支付结果通知controller
 * @author li.jiang
 *
 */
@Controller
@RequestMapping(value="/paynotify")
public final class PayNotifyController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PayNotifyController.class);
    @RequestMapping(value="/confirm", produces = {"text/xml;charset=UTF-8"})
    @ResponseBody
    public String handleNotify(HttpServletRequest request) {
        String xmlData = HttpUtil.getStringBody(request);
        LOGGER.info("接收到的支付通知：");
        LOGGER.info(xmlData);
        try {
            PayNotifyJaxb payNotify = (PayNotifyJaxb) JaxbUnmarshallerHelper.unmarshal(new StringReader(xmlData),
                    new Class<?>[] { PayNotifyJaxb.class });
            payNotify.getAppId();
        } catch (JAXBException e) {
            LOGGER.error("支付通知转换成对象时发生异常", e);
        }

        NotifyResponseJaxb notifyResponse = new NotifyResponseJaxb();
        notifyResponse.setReturnCode(PayNotifyStatus.SUCCESS);
        String xmlResult = "";
        try {
            xmlResult = JaxbMarshallerHelper.marshalToString(notifyResponse);
        } catch (JAXBException e) {
            LOGGER.error("对象转换成XML发生异常", e);
        }
        LOGGER.info("收到支付通知结果，并回复给微信服务器处理结果：");
        LOGGER.info(xmlResult);
        return xmlResult;
    }
}
